/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.startup;

import cn.ac.iie.di.commons.httpserver.framework.server.HttpServer;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.configuration.Configuration;
import cn.ac.iie.di.wx.handler.WxFansCnt;
import cn.ac.iie.di.wx.handler.WxPictureUrl_cache_yizhuang;
import cn.ac.iie.di.wx.handler.WxPictureUrl_new;
import cn.ac.iie.di.wx.handler.WxPictureUrl_new_yizhuang;
import cn.ac.iie.di.wx.handler.WxPictureUrl_old;
import cn.ac.iie.di.wx.handler.WxPictureUrl_old_cache;
import cn.ac.iie.di.wx.handler.WxReadCnt;
import cn.ac.iie.di.wx.handler.WxRealIdQuery;
import cn.ac.iie.di.wx.killHanlder.KillHandler;
import cn.ac.iie.di.wx.mongoservice.MongoHelper;
import cn.ac.iie.di.wx.mongoservice.FansMongoThread;
import cn.ac.iie.di.wx.mongoservice.ReadCntDocinfoMongoThread;
import cn.ac.iie.di.wx.mongoservice.ReadCntWxmsgMongoThread;
import cn.ac.iie.di.wx.mongoservice.RealIdMongoThread;
import cn.ac.iie.di.wx.queueservice.WriteToReadCntFile;
import cn.ac.iie.di.wx.queueservice.WriteTofile;
import cn.ac.iie.di.wx.redis.RedisThread;
import cn.ac.iie.di.wx.redis.RedisUtil;
import cn.ac.iie.di.wx.timerTask.CountTask;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Timer;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Administrator
 */
public class Server {

    static HttpServer httpServer = null;
    static Logger logger = Logger.getLogger(Server.class.getName());

    public static void main(String[] args) {
        PropertyConfigurator.configure(ClassLoader.getSystemClassLoader().getResource("log4j.properties"));
        logger.info("log4j.properties has been configured");
        try {
            init();
            initCount();
            KillHandler killHandler = new KillHandler();
            killHandler.registerSignal("TERM");
            RedisThreadsStarts();
//            MongoUpdateThreadStart();
//            WriteToFileThread();
//            WriteNrdToFileThread
            RedisUtil redisUtil = new RedisUtil((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_HOSTS), (String) RuntimeEnv.getParam(RuntimeEnv.REDIS_MASTER_NAME), Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_DB_NAME)));
            Timer timer = new Timer();
            CountTask countTask = new CountTask(redisUtil);
            timer.schedule(countTask, 1000, 1000);
            startup();
            logger.info("server has been started .");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    public static void init() throws Exception {
        String configurationFileName = "cconfiguration.properties";
        Configuration conf = Configuration.getConfiguration(ClassLoader.getSystemClassLoader().getResource(configurationFileName).getPath());
        if (conf == null) {
            logger.error("reading " + configurationFileName + " is failed.");
        }
        try {
            RuntimeEnv.initialize(conf);///参数，
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXFANSCNTQLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXPICQLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXREADCNTLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXREALIDQLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.MONGOCONNECTLIMIT));
            //创建龙存目录
            File file = new File((String) RuntimeEnv.getParam(RuntimeEnv.PICCACHE));
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            logger.info("init success");
        } catch (Exception ex) {
            logger.error("initializng runtime enviroment is failed for" + ex.getMessage());
        }
    }

    public static void initCount() throws IOException {
        String path = ClassLoader.getSystemClassLoader().getResource("cconfiguration.properties").getPath();
//        logger.info(ClassLoader.getSystemClassLoader().getResource("cconfiguration.properties").getPath());
        Properties prop = new Properties();
        prop.load(new FileInputStream(path));
        RuntimeEnv.wxFansCntQueryCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxFansCntQueryCount", "0")));
        RuntimeEnv.wxReadCntCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxReadCntCount", "0")));
        RuntimeEnv.wxRealIdQueryCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxRealIdQueryCount", "0")));
        RuntimeEnv.wxPictureUrlQueryCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxPictureUrlQueryCount", "0")));
        logger.info(ClassLoader.getSystemClassLoader().getResource("cconfiguration.properties").getPath());

    }

    public static void WriteToFileThread() {
        //写入文件进程
        WriteTofile gtofile = new WriteTofile(
                (String) RuntimeEnv.getParam(RuntimeEnv.WTPATH),
                (String) RuntimeEnv.getParam(RuntimeEnv.FNAME),
                "",
                "",
                RuntimeEnv.picUrlBlockingQueue);
        Thread gthread = new Thread(gtofile);
        gthread.start();
        logger.info("WriteToFileThread start");
    }

    public static void WriteNrdToFileThread() {
        WriteToReadCntFile cntFile = new WriteToReadCntFile(
                (String) RuntimeEnv.getParam(RuntimeEnv.WTPATH),
                (String) RuntimeEnv.getParam(RuntimeEnv.READCNTFNAME),
                "",
                "",
                RuntimeEnv.readCntMqBlockingQueue);
        Thread cnthread = new Thread(cntFile);
        cnthread.start();
    }

    public static void RedisThreadsStarts() {
        RedisUtil redisUtil = new RedisUtil((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_HOSTS),
                (String) RuntimeEnv.getParam(RuntimeEnv.REDIS_MASTER_NAME),
                Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_DB_NAME)));
        RedisThread picRedisThread = new RedisThread(redisUtil, "pic_", RuntimeEnv.wxPictureUrlQueryCount);

        Thread picThread = new Thread(picRedisThread);
        picThread.start();
    }

    public static void startup() {
        try {
            logger.info("startup");
            httpServer = HttpServer.getHttpServer(
                    (String) RuntimeEnv.getParam(RuntimeEnv.JETTY_SERVER),
                    Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.JETTY_PORT)),
                    Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.JETTY_THREADNUM)));
            httpServer.registerContext("/resources");
            httpServer.registerContextHandler("/resources", "/WxPictureUrl", WxPictureUrl_cache_yizhuang.class);//图片URL
            httpServer.registerContextHandler("/resources", "/WxPictureUrl_new", WxPictureUrl_new_yizhuang.class);//图片URL
            httpServer.startup();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

    }
}
